package com.project.contorller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.Employee;
import com.project.dao.IEmployeeDao;
import com.project.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("em")
public class EmController {
    @Autowired
    private IEmployeeService service;

    @RequestMapping("findAll")
    public List<Employee> findAll() {
        return service.findAll();
    }

    @RequestMapping("dimission")
    public String dimission(Integer id) {
        service.dimission(id);
        return "ok";
    }
    //Valid 表示需将提交的数据进行校验  BindingResult用于存放校验失败信息
    @RequestMapping("add")
    public String add(@Valid Employee em, BindingResult br) throws JsonProcessingException {
        if (br.hasErrors()){//判断是否有验证失败信息
            //得到校验失败集合
           List<FieldError> fieldError = br.getFieldErrors();

           //将校验失败集合转换成json字符串发送客户端
            ObjectMapper om = new ObjectMapper();
            String s = om.writeValueAsString(fieldError);
            return s;

        }
        service.add(em);
        return "ok";
    }
    @RequestMapping("findById")
    public Employee findById(Integer id){
        return service.findById(id);
    }
    @RequestMapping("update")
    public String update(Integer id,Integer money){
        service.update(id,money);
        return "ok";
    }

}
